<template>
  <div class="disaster-confirm-container">
    <div class="main-content">
      <!-- 地图容器 -->
      <div id="viewDiv" class="map-view"></div>

      <!-- 右侧功能面板 -->
      <div class="control-panel">
        <el-card class="control-card">
          <template #header>
            <div class="card-header">
              <span>灾情信息管理</span>
              <div class="water-drop"></div>
            </div>
          </template>

          <!-- 表格工具栏 -->
          <div class="table-toolbar">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索灾情名称"
              class="search-input"
              clearable
              @clear="loadDisasters"
              @keyup.enter="searchDisasters"
            >
              <template #append>
                <el-button @click="searchDisasters">
                  <el-icon><Search /></el-icon>
                </el-button>
              </template>
            </el-input>
            <el-button type="primary" @click="loadDisasters">
              <el-icon><Refresh /></el-icon> 刷新数据
            </el-button>
          </div>

          <!-- 灾情信息表格 -->
          <el-table
            :data="disasterList"
            style="width: 100%"
            border
            stripe
            height="calc(100vh - 280px)"
            v-loading="loading"
            @row-click="handleRowClick"
          >
            <el-table-column prop="attributes.Name" label="名称" min-width="120" />
            <el-table-column prop="attributes.DisasterType" label="类型" width="100" />
            <el-table-column label="状态" width="100">
              <template #default="scope">
                <el-tag :type="getStatusType(scope.row)" size="small">
                  {{ getStatusText(scope.row) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="280" fixed="right">
              <template #default="scope">
                <el-button size="small" type="primary" @click.stop="viewDisasterDetail(scope.row)">
                  查看
                </el-button>
                <el-button size="small" type="danger" @click.stop="deleteFeature(scope.row)">
                  删除
                </el-button>
                <el-button
                  size="small"
                  type="success"
                  @click.stop="confirmDisaster(scope.row)"
                  :disabled="isDisasterConfirmed(scope.row)"
                >
                  确认
                </el-button>
                <el-button
                  size="small"
                  type="warning"
                  @click.stop="syncDisaster(scope.row)"
                  :disabled="!isDisasterConfirmed(scope.row)"
                >
                  同步
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页控件 -->
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="totalCount"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-card>
      </div>
    </div>

    <!-- 灾情详情对话框 -->
    <el-dialog
      v-model="showDetailDialog"
      title="灾情详细信息"
      width="60%"
      destroy-on-close
      custom-class="disaster-dialog"
    >
      <div v-if="selectedDisaster" class="disaster-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="名称">{{
            selectedDisaster.attributes.Name
          }}</el-descriptions-item>
          <el-descriptions-item label="灾难类型">
            {{ selectedDisaster.attributes.DisasterType }}
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(selectedDisaster)">
              {{ getStatusText(selectedDisaster) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="描述" :span="2">
            {{ selectedDisaster.attributes.Description }}
          </el-descriptions-item>
        </el-descriptions>

        <div class="photo-container" v-if="selectedDisaster.attributes.Photo">
          <h3>现场照片</h3>
          <img :src="selectedDisaster.attributes.Photo" class="disaster-photo" />
        </div>

        <!-- 受灾情况信息 -->
        <div class="disaster-impact-container" v-if="hasDisasterImpactData(selectedDisaster)">
          <h3>受灾情况</h3>
          <el-descriptions :column="2" border size="small">
            <el-descriptions-item label="受灾人数">
              {{ getDisasterImpactData(selectedDisaster, 'affectedPeople') }} 人
            </el-descriptions-item>
            <el-descriptions-item label="受伤人数">
              {{ getDisasterImpactData(selectedDisaster, 'injuredPeople') }} 人
            </el-descriptions-item>
            <el-descriptions-item label="死亡人数">
              {{ getDisasterImpactData(selectedDisaster, 'deathCount') }} 人
            </el-descriptions-item>
            <el-descriptions-item label="无家可归人数">
              {{ getDisasterImpactData(selectedDisaster, 'homelessPeople') }} 人
            </el-descriptions-item>
            <el-descriptions-item label="经济损失">
              {{ getDisasterImpactData(selectedDisaster, 'economicLoss') }} 万元
            </el-descriptions-item>
            <el-descriptions-item label="受灾面积">
              {{ getDisasterImpactData(selectedDisaster, 'affectedArea') }} km²
            </el-descriptions-item>
            <el-descriptions-item label="救援队伍数量">
              {{ getDisasterImpactData(selectedDisaster, 'rescueTeams') }} 个
            </el-descriptions-item>
            <el-descriptions-item label="救援人员数量">
              {{ getDisasterImpactData(selectedDisaster, 'rescuePersonnel') }} 人
            </el-descriptions-item>
          </el-descriptions>
        </div>

        <div class="message-container" v-if="isDisasterConfirmed(selectedDisaster)">
          <h3>确认信息</h3>
          <el-form label-width="120px">
            <el-form-item label="确认时间">
              {{ getConfirmTime(selectedDisaster) }}
            </el-form-item>
            <el-form-item label="确认备注">
              {{ getConfirmNote(selectedDisaster) }}
            </el-form-item>
            <el-form-item label="同步状态">
              <el-tag :type="getSyncStatusType(selectedDisaster)">
                {{ getSyncStatusText(selectedDisaster) }}
              </el-tag>
            </el-form-item>
            <el-form-item v-if="isSynced(selectedDisaster)" label="同步时间">
              {{ getSyncTime(selectedDisaster) }}
            </el-form-item>
          </el-form>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showDetailDialog = false">关闭</el-button>
          <el-button
            type="success"
            @click="confirmDisaster(selectedDisaster)"
            :disabled="isDisasterConfirmed(selectedDisaster)"
          >
            确认灾情
          </el-button>
          <el-button
            type="warning"
            @click="syncDisaster(selectedDisaster)"
            :disabled="!isDisasterConfirmed(selectedDisaster)"
          >
            同步信息
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 确认灾情对话框 -->
    <el-dialog
      v-model="showConfirmDialog"
      title="确认灾情信息"
      width="60%"
      destroy-on-close
      custom-class="confirm-dialog"
    >
      <el-form :model="confirmForm" label-width="120px" ref="confirmFormRef">
        <el-form-item label="灾情名称" prop="name">
          <el-input v-model="confirmForm.name" disabled></el-input>
        </el-form-item>

        <el-divider content-position="center">受灾情况</el-divider>

        <div class="disaster-impact-form">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="受灾人数" prop="affectedPeople">
                <el-input-number
                  v-model="confirmForm.affectedPeople"
                  :min="0"
                  :precision="0"
                  :step="10"
                  style="width: 100%"
                ></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="受伤人数" prop="injuredPeople">
                <el-input-number
                  v-model="confirmForm.injuredPeople"
                  :min="0"
                  :precision="0"
                  :step="5"
                  style="width: 100%"
                ></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="死亡人数" prop="deathCount">
                <el-input-number
                  v-model="confirmForm.deathCount"
                  :min="0"
                  :precision="0"
                  style="width: 100%"
                ></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="无家可归人数" prop="homelessPeople">
                <el-input-number
                  v-model="confirmForm.homelessPeople"
                  :min="0"
                  :precision="0"
                  :step="10"
                  style="width: 100%"
                ></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="经济损失(万元)" prop="economicLoss">
                <el-input-number
                  v-model="confirmForm.economicLoss"
                  :min="0"
                  :precision="2"
                  :step="100"
                  style="width: 100%"
                ></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="受灾面积(km²)" prop="affectedArea">
                <el-input-number
                  v-model="confirmForm.affectedArea"
                  :min="0"
                  :precision="2"
                  :step="1"
                  style="width: 100%"
                ></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="救援队伍数量" prop="rescueTeams">
                <el-input-number
                  v-model="confirmForm.rescueTeams"
                  :min="0"
                  :precision="0"
                  style="width: 100%"
                ></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="救援人员数量" prop="rescuePersonnel">
                <el-input-number
                  v-model="confirmForm.rescuePersonnel"
                  :min="0"
                  :precision="0"
                  :step="10"
                  style="width: 100%"
                ></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <el-divider content-position="center">备注信息</el-divider>

        <el-form-item label="确认备注" prop="note">
          <el-input
            v-model="confirmForm.note"
            type="textarea"
            :rows="4"
            placeholder="请输入确认备注信息"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showConfirmDialog = false">取消</el-button>
          <el-button type="primary" @click="showSyncDialog = true">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 同步信息对话框 -->
    <el-dialog
      v-model="showSyncDialog"
      title="同步灾情信息"
      width="40%"
      destroy-on-close
      custom-class="sync-dialog"
    >
      <div class="sync-content">
        <el-alert
          title="确认要将此灾情信息同步到其他系统吗？"
          type="warning"
          :closable="false"
          show-icon
        >
          <p>同步后，该灾情信息将被推送到相关部门和救援系统。</p>
        </el-alert>

        <div class="sync-info" v-if="selectedDisaster">
          <h3>灾情信息</h3>
          <p><strong>名称：</strong>{{ selectedDisaster.attributes.Name }}</p>
          <p><strong>类型：</strong>{{ selectedDisaster.attributes.DisasterType }}</p>
          <p>
            <strong>位置：</strong>经度: {{ selectedDisaster.geometry.x.toFixed(6) }}, 纬度:
            {{ selectedDisaster.geometry.y.toFixed(6) }}
          </p>

          <div v-if="hasDisasterImpactData(selectedDisaster)" class="disaster-impact-summary">
            <h4>受灾情况摘要</h4>
            <p>
              <strong>受灾人数：</strong>{{ confirmForm.affectedPeople }} 人 |
              <strong>受伤：</strong>{{ confirmForm.injuredPeople }} 人 | <strong>死亡：</strong
              >{{ confirmForm.deathCount }} 人
            </p>
            <p>
              <strong>经济损失：</strong>{{ confirmForm.economicLoss }} 万元 |
              <strong>受灾面积：</strong>{{ confirmForm.affectedArea }} km²
            </p>
          </div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showSyncDialog = false">取消</el-button>
          <el-button type="primary" @click="submitConfirm">确认同步</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus'
import { Search, Refresh } from '@element-plus/icons-vue'
import Map from '@arcgis/core/Map'
import MapView from '@arcgis/core/views/MapView'
import FeatureLayer from '@arcgis/core/layers/FeatureLayer'
import gaodeLayer from '@/utils/GaoDeBaseLayer'
import gcoord from 'gcoord'

// 状态变量
const loading = ref(false)
const disasterList = ref<any[]>([])
const selectedDisaster = ref<any>(null)
const showDetailDialog = ref(false)
const showConfirmDialog = ref(false)
const showSyncDialog = ref(false)
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const totalCount = ref(0)

// 确认表单
const confirmFormRef = ref<FormInstance | null>(null)
const confirmForm = ref({
  name: '',
  note: '',
  // 受灾情况字段
  affectedPeople: 0, // 受灾人数
  injuredPeople: 0, // 受伤人数
  deathCount: 0, // 死亡人数
  economicLoss: 0, // 经济损失(万元)
  affectedArea: 0, // 受灾面积(平方公里)
  homelessPeople: 0, // 无家可归人数
  rescueTeams: 0, // 救援队伍数量
  rescuePersonnel: 0, // 救援人员数量
})

// 地图和图层引用
let view: MapView | null = null
let disasterLayer: FeatureLayer | null = null

onMounted(() => {
  initMap()
  loadDisasters()
})

onUnmounted(() => {
  if (view) {
    view = null
  }
})

// 初始化地图
const initMap = () => {
  try {
    // 创建地图实例
    const map = new Map({
      basemap: {
        baseLayers: [gaodeLayer],
      },
    })

    // 创建地图视图
    view = new MapView({
      container: 'viewDiv',
      map: map,
      center: [117.0203, 36.6683], // 山东省济南市的经纬度
      zoom: 10,
    })

    // 创建灾难点要素图层
    disasterLayer = new FeatureLayer({
      url: 'https://services7.arcgis.com/chXsWZj8U6NqFZb6/arcgis/rest/services/DisasterDetectionAndRescueSystem/FeatureServer/0',
      outFields: ['*'], // 获取所有字段
      renderer: {
        type: 'simple',
        symbol: {
          type: 'simple-marker',
          color: [255, 0, 0],
          outline: {
            color: [255, 255, 255],
            width: 2,
          },
          size: 12,
        },
      },
      popupTemplate: {
        title: '{Name}',
        content: (feature :any) => {
          const attributes = feature.graphic.attributes;
          let content = `
            <div class="popup-content">
              <div class="popup-section">
                <h3>基本信息</h3>
                <p><strong>名称：</strong>${attributes.Name || '无'}</p>
                <p><strong>灾难类型：</strong>${attributes.DisasterType || '无'}</p>
                <p><strong>描述：</strong>${attributes.Description || '无'}</p>
              </div>
          `;

          // 检查是否有DisasterMessageJson数据
          if (attributes.DisasterMessageJson) {
            try {
              const messageData = JSON.parse(attributes.DisasterMessageJson);

              // 添加确认状态信息
              content += `
                <div class="popup-section">
                  <h3>状态信息</h3>
                  <p><strong>状态：</strong>${messageData.confirmed ? '已确认' : '未确认'}</p>
              `;

              if (messageData.confirmed) {
                content += `<p><strong>确认时间：</strong>${new Date(messageData.confirmTime).toLocaleString()}</p>`;
                if (messageData.confirmNote) {
                  content += `<p><strong>确认备注：</strong>${messageData.confirmNote}</p>`;
                }
              }

              content += `<p><strong>同步状态：</strong>${messageData.synced ? '已同步' : '未同步'}</p>`;
              if (messageData.synced && messageData.syncTime) {
                content += `<p><strong>同步时间：</strong>${new Date(messageData.syncTime).toLocaleString()}</p>`;
              }
              content += `</div>`;

              // 添加受灾情况数据
              if (messageData.disasterImpact) {
                const impact = messageData.disasterImpact;
                content += `
                  <div class="popup-section">
                    <h3>受灾情况</h3>
                    <p><strong>受灾人数：</strong>${impact.affectedPeople || 0} 人</p>
                    <p><strong>受伤人数：</strong>${impact.injuredPeople || 0} 人</p>
                    <p><strong>死亡人数：</strong>${impact.deathCount || 0} 人</p>
                    <p><strong>无家可归人数：</strong>${impact.homelessPeople || 0} 人</p>
                    <p><strong>经济损失：</strong>${impact.economicLoss || 0} 万元</p>
                    <p><strong>受灾面积：</strong>${impact.affectedArea || 0} km²</p>
                    <p><strong>救援队伍数量：</strong>${impact.rescueTeams || 0} 个</p>
                    <p><strong>救援人员数量：</strong>${impact.rescuePersonnel || 0} 人</p>
                  </div>
                `;
              }
            } catch (e) {
              console.error('解析DisasterMessageJson失败:', e);
            }
          }

          content += `</div>`;
          return content;
        },
        outFields: ['*'],
      },
    })

    // 添加图层到地图
    map.add(disasterLayer)
  } catch (error) {
    console.error('初始化地图失败:', error)
    ElMessage.error('初始化地图失败')
  }
}

// 加载灾情数据
const loadDisasters = async () => {
  if (!disasterLayer) return

  loading.value = true
  try {
    // 构建查询参数
    const query = disasterLayer.createQuery()
    query.outFields = ['*']
    query.returnGeometry = true
    query.where = '1=1' // 查询所有记录
    query.start = (currentPage.value - 1) * pageSize.value
    query.num = pageSize.value

    // 如果有搜索关键词，添加到查询条件
    if (searchKeyword.value) {
      query.where = `Name LIKE '%${searchKeyword.value}%'`
    }

    // 执行查询
    const results = await disasterLayer.queryFeatures(query)

    // 获取总记录数
    const countQuery = disasterLayer.createQuery()
    countQuery.where = query.where
    countQuery.returnGeometry = false
    countQuery.outFields = []
    const countResults = await disasterLayer.queryFeatureCount(countQuery)
    totalCount.value = countResults

    // 更新列表数据
    disasterList.value = results.features.map((feature) => {
      // 在存储前对结果数据进行序列化处理，移除不可序列化的属性
      const safeFeature = JSON.parse(
        JSON.stringify(feature, (key, value) => {
          // 过滤掉ArcGIS特殊属性或不可序列化的对象
          if (key === '__accessor__' || typeof value === 'function' || key.startsWith('_')) {
            return undefined
          }
          return value
        }),
      )
      return safeFeature
    })
    console.log(disasterList.value)
  } catch (error) {
    console.error('加载灾情数据失败:', error)
    ElMessage.error('加载灾情数据失败')
  } finally {
    loading.value = false
  }
}

// 搜索灾情
const searchDisasters = () => {
  currentPage.value = 1 // 重置到第一页
  loadDisasters()
}

// 处理分页大小变化
const handleSizeChange = (val: number) => {
  pageSize.value = val
  loadDisasters()
}

// 处理页码变化
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  loadDisasters()
}

// 处理行点击事件
const handleRowClick = (row: any) => {
  viewDisasterDetail(row)
}

// 查看灾情详情
const viewDisasterDetail = (disaster: any) => {
  selectedDisaster.value = disaster
  showDetailDialog.value = true

  // 在地图上高亮显示选中的灾情点
  highlightDisasterOnMap(disaster)
}
// 删除灾情点
const deleteFeature = async (disaster: any) => {
  if (!disaster || !disasterLayer) return

  try {
    const objectId = disaster.attributes.OBJECTID
    const result = await disasterLayer.applyEdits({
      deleteFeatures: [{ objectId: objectId }],
    })

    if (result.deleteFeatureResults && result.deleteFeatureResults.length > 0) {
      ElMessage.success('删除成功')
      loadDisasters() // 刷新列表
    } else {
      ElMessage.error('删除失败')
    }
  } catch (error) {
    console.error('删除灾情失败:', error)
    ElMessage.error('删除失败')
  }
}

// 在地图上高亮显示灾情点
const highlightDisasterOnMap = (disaster: any) => {
  if (!view) return
  console.log(disaster)
  // 将Web Mercator坐标转换为WGS84坐标
  const disasterPoint = gcoord.transform(
    [disaster.geometry.x, disaster.geometry.y],
    gcoord.EPSG3857,
    gcoord.WGS84,
  )
  // 将视图中心移动到选中点
  view.goTo(
    {
      center: [disasterPoint[0], disasterPoint[1]],
      zoom: 15,
    },
    { duration: 1000 },
  )
}

// 确认灾情
const confirmDisaster = (disaster: any) => {
  if (!disaster) return

  selectedDisaster.value = disaster
  console.log(disaster)
  confirmForm.value.name = disaster.attributes.Name
  confirmForm.value.note = ''
  showConfirmDialog.value = true
}

// 提交确认
const submitConfirm = async () => {
  if (!selectedDisaster.value || !disasterLayer) return

  try {
    // 准备DisasterMessageJson数据
    const messageData = {
      confirmed: true,
      confirmTime: selectedDisaster.value.attributes.DisasterMessageJson?.confirmTime || new Date().toISOString(),
      confirmNote: confirmForm.value.note,
      synced: true,
      syncTime: new Date().toISOString(),
      // 添加受灾情况数据
      disasterImpact: {
        affectedPeople: confirmForm.value.affectedPeople,
        injuredPeople: confirmForm.value.injuredPeople,
        deathCount: confirmForm.value.deathCount,
        economicLoss: confirmForm.value.economicLoss,
        affectedArea: confirmForm.value.affectedArea,
        homelessPeople: confirmForm.value.homelessPeople,
        rescueTeams: confirmForm.value.rescueTeams,
        rescuePersonnel: confirmForm.value.rescuePersonnel,
        note: confirmForm.value.note,
      },
    }

    // 更新要素
    const objectId = selectedDisaster.value.attributes.OBJECTID
    const result = await disasterLayer.applyEdits({
      updateFeatures: [
        {
          attributes: {
            OBJECTID: objectId,
            DisasterMessageJson: JSON.stringify(messageData),
          },
        } as any,
      ],
    })

    if (result.updateFeatureResults && result.updateFeatureResults.length > 0) {
      ElMessage.success('灾情信息已确认')
      showConfirmDialog.value = false
      showDetailDialog.value = false

      // 更新本地数据
      selectedDisaster.value.attributes.DisasterMessageJson = JSON.stringify(messageData)
      // loadDisasters()
    } else {
      ElMessage.error('确认灾情失败')
    }
  } catch (error) {
    console.error('确认灾情失败:', error)
    ElMessage.error('确认灾情失败')
  }
}

// 同步灾情信息
const syncDisaster = (disaster: any) => {
  if (!disaster) return

  selectedDisaster.value = disaster
  confirmForm.value.name = disaster.attributes.Name
  // 序列化DisasterMessageJson数据
  const messageJson = disaster.attributes.DisasterMessageJson
  if (messageJson) {
    const messageData = JSON.parse(messageJson)
    if (messageData.disasterImpact) {
      confirmForm.value.affectedPeople = messageData.disasterImpact.affectedPeople || 0
      confirmForm.value.injuredPeople = messageData.disasterImpact.injuredPeople || 0
      confirmForm.value.deathCount = messageData.disasterImpact.deathCount || 0
      confirmForm.value.economicLoss = messageData.disasterImpact.economicLoss || 0
      confirmForm.value.affectedArea = messageData.disasterImpact.affectedArea || 0
      confirmForm.value.homelessPeople = messageData.disasterImpact.homelessPeople || 0
      confirmForm.value.rescueTeams = messageData.disasterImpact.rescueTeams || 0
      confirmForm.value.rescuePersonnel = messageData.disasterImpact.rescuePersonnel || 0
      confirmForm.value.note = messageData.disasterImpact.note || ''
    }
  }

  showConfirmDialog.value = true
}

// 获取灾情状态类型
const getStatusType = (disaster: any) => {
  if (!disaster) return ''

  if (isSynced(disaster)) {
    return 'success'
  } else if (isDisasterConfirmed(disaster)) {
    return 'warning'
  } else {
    return 'info'
  }
}

// 获取灾情状态文本
const getStatusText = (disaster: any) => {
  if (!disaster) return ''

  if (isSynced(disaster)) {
    return '已同步'
  } else if (isDisasterConfirmed(disaster)) {
    return '已确认'
  } else {
    return '未确认'
  }
}

// 获取同步状态类型
const getSyncStatusType = (disaster: any) => {
  return isSynced(disaster) ? 'success' : 'info'
}

// 获取同步状态文本
const getSyncStatusText = (disaster: any) => {
  return isSynced(disaster) ? '已同步' : '未同步'
}

// 检查灾情是否已确认
const isDisasterConfirmed = (disaster: any) => {
  if (!disaster) return false

  try {
    const messageJson = disaster.attributes.DisasterMessageJson
    if (!messageJson) return false

    const messageData = JSON.parse(messageJson)
    return messageData.confirmed === true
  } catch (e) {
    return false
  }
}

// 检查灾情是否已同步
const isSynced = (disaster: any) => {
  if (!disaster) return false

  try {
    const messageJson = disaster.attributes.DisasterMessageJson
    if (!messageJson) return false

    const messageData = JSON.parse(messageJson)
    return messageData.synced === true
  } catch (e) {
    return false
  }
}

// 获取确认时间
const getConfirmTime = (disaster: any) => {
  if (!disaster) return ''

  try {
    const messageJson = disaster.attributes.DisasterMessageJson
    if (!messageJson) return ''

    const messageData = JSON.parse(messageJson)
    if (!messageData.confirmTime) return ''

    return new Date(messageData.confirmTime).toLocaleString()
  } catch (e) {
    return ''
  }
}

// 获取确认备注
const getConfirmNote = (disaster: any) => {
  if (!disaster) return ''

  try {
    const messageJson = disaster.attributes.DisasterMessageJson
    if (!messageJson) return ''

    const messageData = JSON.parse(messageJson)
    return messageData.confirmNote || ''
  } catch (e) {
    return ''
  }
}

// 获取同步时间
const getSyncTime = (disaster: any) => {
  if (!disaster) return ''

  try {
    const messageJson = disaster.attributes.DisasterMessageJson
    if (!messageJson) return ''

    const messageData = JSON.parse(messageJson)
    if (!messageData.syncTime) return ''

    return new Date(messageData.syncTime).toLocaleString()
  } catch (e) {
    return ''
  }
}

// 检查是否有受灾情况数据
const hasDisasterImpactData = (disaster: any) => {
  if (!disaster) return false

  try {
    const messageJson = disaster.attributes.DisasterMessageJson
    if (!messageJson) return false

    const messageData = JSON.parse(messageJson)
    return messageData.disasterImpact !== undefined
  } catch (e) {
    return false
  }
}

// 获取受灾情况数据
const getDisasterImpactData = (disaster: any, field: string) => {
  if (!disaster) return ''

  try {
    const messageJson = disaster.attributes.DisasterMessageJson
    if (!messageJson) return ''

    const messageData = JSON.parse(messageJson)
    if (!messageData.disasterImpact) return ''

    return messageData.disasterImpact[field] || '0'
  } catch (e) {
    return ''
  }
}
</script>

<style scoped>
.disaster-confirm-container {
  width: 100%;
  height: 100%;
  position: relative;
}

.main-content {
  display: flex;
  height: 100%;
  padding: 16px;
  box-sizing: border-box;
  gap: 16px;
}

.map-view {
  flex: 1;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
  min-height: 500px;
}

.control-panel {
  width: 600px;
  z-index: 10;
  display: flex;
  flex-direction: column;
}

.control-card {
  background-color: rgba(255, 255, 255, 0.98);
  border-radius: 16px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.2);
  border: none;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: relative;
  color: #2c3e50;
  font-weight: bold;
  font-size: 18px;
  padding-bottom: 8px;
  border-bottom: 2px solid #eaeaea;
}

.water-drop {
  position: absolute;
  top: -10px;
  right: -10px;
  width: 30px;
  height: 30px;
  background-color: rgba(64, 158, 255, 0.2);
  border-radius: 50%;
  z-index: -1;
}

/* 受灾情况表单样式 */
.disaster-impact-form {
  margin: 10px 0 20px 0;
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 8px;
  border: 1px solid #eaeaea;
}

/* 受灾情况信息显示样式 */
.disaster-impact-info {
  margin-top: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
}

.disaster-impact-info h3 {
  margin-top: 0;
  margin-bottom: 15px;
  color: #409eff;
  font-size: 16px;
  border-bottom: 1px solid #dcdfe6;
  padding-bottom: 8px;
}

/* 同步对话框中的受灾情况摘要 */
.disaster-impact-summary {
  margin-top: 15px;
  padding: 10px;
  background-color: #f0f9eb;
  border-radius: 6px;
  border-left: 3px solid #67c23a;
}

.disaster-impact-summary h4 {
  margin-top: 0;
  margin-bottom: 10px;
  color: #67c23a;
  font-size: 14px;
}

.disaster-impact-summary p {
  margin: 5px 0;
  line-height: 1.5;
  font-size: 13px;
}

.table-toolbar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 16px;
  gap: 10px;
}

.search-input {
  width: 250px;
}

.pagination-container {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}

.disaster-detail {
  padding: 16px;
}

.photo-container {
  margin-top: 20px;
}

.disaster-photo {
  max-width: 100%;
  max-height: 300px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.disaster-impact-container {
  margin-top: 20px;
  margin-bottom: 20px;
  padding: 15px;
  background-color: rgba(245, 247, 250, 0.8);
  border-radius: 8px;
  border-left: 4px solid #409eff;
}

.disaster-impact-container h3 {
  color: #409eff;
  margin-top: 0;
  margin-bottom: 15px;
  font-size: 16px;
  font-weight: 600;
}

.message-container {
  margin-top: 20px;
  padding: 16px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.sync-content {
  padding: 20px 0;
}

.sync-info {
  margin-top: 20px;
  padding: 16px;
  background-color: #f8f9fa;
  border-radius: 8px;
}
</style>
